package com.ziJing.multithreading.sync.c_02_interview_A1B2C3;

import sun.tools.jconsole.MaximizableInternalFrame;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program Multithreading
 * @description: notifyAll --> 如果生产者线程只想叫醒消费者线程呢？下面这种实现方式
 * @author: zhangbo
 * @create: 2022/05/04 02:40
 */
public class MyContainer2<T> {

    final private LinkedList<T> lists = new LinkedList<>();
    //最多10个元素
    final private int MAX = 10;
    private int count = 0;

    private Lock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();


    private void put(T t) {
        lock.lock();
        try {
            //想想为什么用while而不是if
            // wait一次就能保证下次小于 MAX 了么
            while (lists.size() == MAX) {
                producer.wait();
            }

            lists.add(t);
            ++count;

            //只通知消费者线程进行消费
            consumer.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }


    public T get() {
        T t = null;
        lock.lock();
        try {
            while (lists.size() == 0) {
                this.wait();
            }

            t = lists.removeFirst();
            count--;

            //只通知生产者进行生产
            producer.signalAll();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return t;
    }



    public static void main(String[] args) {
        MyContainer2<String> c = new MyContainer2<>();

        //启动消费者线程
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println(c.get());
                }
            }, "c" + i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //启动生产者线程
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 25; j++) {
                    c.put(Thread.currentThread().getName() + " " + j);
                }
            }, "p" + i).start();
        }
    }
}
